package com.lz.ssm.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lz.ssm.domain.Employee;
import com.lz.ssm.mapper.EmployeeMapper;
import com.lz.ssm.mapper.RoleMapper;
import com.lz.ssm.qo.EmployeeQueryObject;
import com.lz.ssm.qo.PageResult;
import com.lz.ssm.service.IEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 处理部门服务的实现
 *
 * @author zzz
 */
@Service
public class EmployeeServiceImpl implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public void delete(Long id) {
        roleMapper.deleteRoleIdByEmployeeId(id);
        employeeMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void save(Employee employee, Long[] roleIds) {
        employeeMapper.insert(employee);
        saveRoletion(employee, roleIds);
    }

    @Override
    public Employee get(Long id) {
        Employee employee = employeeMapper.selectByPrimaryKey(id);
        return employee;
    }

    @Override
    public List<Employee> listAll() {
        List<Employee> employees = employeeMapper.selectAll();
        return employees;
    }

    @Override
    public void update(Employee employee, Long[] roleIds) {
        //HashSet set = roleMapper.selectRoleIdByEmployeeId(employee.getId());
        roleMapper.deleteRoleIdByEmployeeId(employee.getId());
        //int i=1/0;
        employeeMapper.updateByPrimaryKey(employee);
        saveRoletion(employee, roleIds);
    }

    private void saveRoletion(Employee employee, Long[] roleIds) {
        if (roleIds != null && roleIds.length > 0) {
            for (Long roleId : roleIds) {
                employeeMapper.insertRelation(employee.getId(), roleId);
            }
        }
    }

    @Override
    public PageInfo<Employee> query(EmployeeQueryObject qo) {
//        int count = employeeMapper.queryCount(qo);
//        return new PageResult<>(qo.getCurrentPage(), qo.getPageSize(), count,
//                count == 0 ? Collections.emptyList() : employeeMapper.queryEmp(qo));
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        return new PageInfo<>(employeeMapper.queryEmp(qo));
    }

    @Override
    public Employee login(String username, String password) {

        // 查询数据库中是否有匹配的数据
        Employee employee = employeeMapper.selectByUsernameAndPassword(username, password);

        if (employee == null) {
            //通知调用者出现异常
            throw new RuntimeException("账号和密码不匹配");
        }
        return employee;
    }
}
